from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from django.contrib.auth.hashers import make_password, check_password
from myadmin.models import Users,Types,Goods,Address,Order,OrderInfo
from myadmin.views.views import upload
# Create your views here.

# 获取导航分类
def gettype():
	# 获取所有的二级分类
	data = Types.objects.exclude(pid=0)
	return data

# 首页
def index(request):
	# data = [
	# 	{
	# 		'name':'服装',
	# 		'sub':[
	# 			{'name':'男装','sub':[{'title':''},{},{}]},
	# 			{'name':'女装','sub':[{'title':''},{},{}]},
			
	# 		]
	# 	},
	# 	{
	# 		'name':'数码',
	# 		'sub':[
	# 			{'name':'相机','sub':[{'tilte':''},{},{}]},
	# 			{'name':'手机','sub':[{'title':''},{},{}]}
	# 		]

	# 	}
	# ]

	# 获取所有的顶级分类
	data = Types.objects.filter(pid=0)
	for x in data:
		x.sub = Types.objects.filter(pid=x.id)
		for v in x.sub:
			v.sub = Goods.objects.filter(typeid=v.id)[:4]
		

	context = {'typelist':gettype(),'nvalist':data}
	return render(request,'home/index.html',context)

def list(request,tid):
	# 获取当前的分类对象
	tobj = Types.objects.get(id = tid)


	if tobj.pid == 0:
		# 顶级分类
		data = tobj
		data.sub = Types.objects.filter(pid = tobj.id)

		idlist=[]
		for i in data.sub:
			idlist.append(i.id)

		data.goods = Goods.objects.filter(typeid__in=idlist )
		
	else:
		# 二级分类
		data = Types.objects.get(id = tobj.pid)
		data.sub = Types.objects.filter(pid = tobj.pid)
		data.goods = Goods.objects.filter(typeid = tobj.id)
		data.obj = tobj


	context = {'typelist':gettype(),'data':data}
	
	return render(request,'home/list.html',context)

def info(request,gid):
	gobj = Goods.objects.get(id = gid) 



	context = {'typelist':gettype(),'data':gobj}
	# return HttpResponse('info')
	return render(request,'home/info.html',context)
	

# 注册账号
def register(request):
	if request.method == 'GET':
		return render(request,'home/register.html')
	elif request.method == 'POST':
		if request.POST['vcode'].lower() != request.session['verifycode']:
			return HttpResponse('<script>alert("验证码错误");location.href="/register/";</script>')	

		password = request.POST['password']
		res = Users.objects.filter(username = request.POST['username']).exists()
		if res:
			return HttpResponse('<script>alert("用户名已存在");location.href="/register/";</script>')	
		else:
			obj = Users()
			obj.username = request.POST['username']
			obj.password = make_password(request.POST['password'], None, 'pbkdf2_sha256')
			obj.save()
			request.session['VipUser'] = {'name':obj.username,'pic':obj.picurl,'uid':obj.id}
			
			return HttpResponse('<script>alert("注册成功，欢迎登陆");location.href="/";</script>')	




# 登陆
def login(request):
	if request.method == 'GET':
		return render(request,'home/login.html')
	elif request.method == 'POST':
		if request.POST['vcode'].lower() != request.session['verifycode'].lower():
			return HttpResponse('<script>alert("验证码错误");location.href="/login/";</script>')
		else:
			obj = Users.objects.filter(username = request.POST['username'])
			if obj:
				obj = obj[0]
				if check_password(request.POST['password'],obj.password):
					# 
					request.session['VipUser'] = {'name':obj.username,'pic':obj.picurl,'uid':obj.id}
					return HttpResponse('<script>alert("登陆成功");location.href="/";</script>')
					
			
			return HttpResponse('<script>alert("用户名或密码错误");location.href="/login/";</script>')

	
# 退出
def logout(request):
	del request.session['VipUser']
	return HttpResponse('<script>alert("退出登录成功");location.href="/login/";</script>')


# 购物车
def cartlist(request):
	context = {'typelist':gettype()}
	return render(request,'home/cartlist.html',context)

# 加入购物车
def cartadd(request):
	try:
		# 接收商品id
		gid = request.GET.get('gid')
		# 接收商品数量
		num = int(request.GET.get('num'))

		# 获取购物车数据
		data = request.session.get('cart',{})

		# 判断新添加的商品是否已存在
		# { 1:{},2:{} }
		if gid in data:
			# 如果已存在,找到商品，修改数量
			data[gid]['num'] += num
		else:
			# 如果不存在，获取商品信息
			goods = Goods.objects.get(id=gid)
			# 把新的商品信息，追加到data数据库中
			data[gid]={'id':goods.id,'title':goods.title,'price':str(goods.price),'pic':goods.pic,'num':num}

		# 把数据加入到session中
		request.session['cart'] = data 

		return JsonResponse({'code':0,'msg':'加入购物车成功'})
	except:
		return JsonResponse({'code':1,'msg':'加入购物车失败'})


def cartclear(request):
	request.session['cart']={}
	return HttpResponse('<script>location.href="/cart/list"</script>')



def cartlistnumadd(request):
	try:

		# 获取商品数量
		num = int(request.GET['num'])
		# 获取商品id
		gid = request.GET['gid']


		# 获取购物车数据
		data = request.session['cart']
		# 找到商品，修改数量
		data[gid]['num']=num
		# 改变session中的数据
		request.session['cart'] = data


		# 根据商品id获得商品价格
		gobj = Goods.objects.get(id = gid)
		price = float(gobj.price)
		
		# 购物车中多个商品的总价
		total = price * num
		total = '{:.2f}'.format(total)
		print(total)
		return JsonResponse({'code':0,'total':total})
	except:
		return JsonResponse({'code':1,'msg':'计算失败'})



def cartlistnumreduce(request):
	try:
		# 获取商品数量
		num = int(request.GET['num'])
		# 获取商品id
		gid = request.GET['gid']

		# 获取购物车数据
		data = request.session['cart']
		# 找到商品，修改数量
		data[gid]['num']=num
		# 改变session中的数据
		request.session['cart'] = data


		# 根据商品id获得商品价格
		gobj = Goods.objects.get(id = gid)
		price = float(gobj.price)
		
		# 购物车中多个商品的总价
		total = price * num
		total = '{:.2f}'.format(total)
		
		return JsonResponse({'code':0,'total':total})
	except:
		return JsonResponse({'code':1,'msg':'计算失败'})

# 删除购物车中的指定商品
def cartlistdel(request):
	try:
		# 获取要删除的商品的id
		gid = request.GET.get('gid')

		# 获取购物车数据
		data = request.session['cart']
		# 删除要删除的购物车商品
		data.pop(gid)
		# 改变session中的数据
		request.session['cart'] = data
		return JsonResponse({'code':0,'msg':'删除成功'})
	except:
		return JsonResponse({'code':1,'msg':'删除失败'})

# 确认订单
def orderconfirm(request):
	if request.method == 'GET':
		#获取用户选择的产品
		ids = request.GET['ids'].split(',')
		
		# 从session中读取购物车信息
		cartdata = request.session['cart']
		orderdata = {}

		for x in cartdata:
			if x in ids:
				orderdata[x] = cartdata[x]
		# 把用户选择购买的商品存入session
		request.session['order'] = orderdata


		# 需要让用户确认收获地址 获取当前用户的所有地址信息
		address = Address.objects.filter(uid = request.session['VipUser']['uid'])

		context = {'typelist':gettype(),'address':address}
		
		return render(request,'home/orderconfirm.html',context)
	elif request.method == 'POST':
		# 执行地址添加
		obj = Address()
		obj.uid = Users.objects.get(id=request.session['VipUser']['uid'])
		obj.aname = request.POST['aname']
		obj.aads = request.POST['aads']
		obj.aphone = request.POST['aphone']
		# 状态修改
		s = request.POST.get('status',0)
		# 判断当前如果设置为默认值
		if s == '1' :
			# 把其它的地址修改状态为0
			obs = Address.objects.filter(status=1)
			for x in obs:
				x.status = 0
				x.save()

		obj.status = s
		obj.save()
		return HttpResponse('<script>alert("地址添加成功");location.href="/order/confirm/?ids='+request.GET['ids']+'"</script>')


# 生成订单
def ordercreate(request):
	# 在session中获取订单数据
	data = request.session['order']
	totalprice = 0
	totalnum = 0

	for x in data:
		n = float(data[x]['price']) * data[x]['num']
		totalprice += n 
		totalnum += data[x]['num'] 

	# 创建订单
	order = Order()
	order.uid = Users.objects.get(id=request.session['VipUser']['uid'])
	order.address = Address.objects.get(id=request.POST['addressid'])
	order.totalprice = totalprice
	order.totalnum = totalnum
	order.status = 1
	order.save()

	# 读取购物车数据
	cart = request.session['cart']
	# 创建订单详情
	for x in data:
		orderinfo = OrderInfo()
		# 订单号
		orderinfo.orderid = order
		# 获取当前购买的商品对象
		goods = Goods.objects.get(id=x)
		orderinfo.gid = goods
		orderinfo.num = data[x]['num']
		orderinfo.price = data[x]['price']
		orderinfo.save()

		# 清除购物车商品数据
		del cart[x]

		# 修改商品的购买数量
		goods.num += data[x]['num']
		goods.storage -= data[x]['num']
		goods.save()

	# 清空session中的订单数据
	request.session['order'] = {}
	# 更新购物车
	request.session['cart'] = cart

	# 跳到付款页面
	return HttpResponse('<script>alert("订单创建成功，请立即支付");location.href="/order/buy/?orderid='+str(order.id)+'";</script>')



# 付款页面
def orderbuy(request):
	orderid = request.GET.get('orderid',None)
	if orderid:
		# 通过订单id 获取订单信息，并展示
		order = Order.objects.get(id=orderid)
		context ={'order':order}
		return render(request,'home/buy.html',context)

# 我的订单
def myorder(request):
	# 获取当前登录用户的搜有订单信息
	orders = Order.objects.filter(uid=request.session['VipUser']['uid'])
	print(orders)
	context = {'orders':orders}
	return render(request,'home/myorder.html',context)

# 订单详情
def myorderinfo(request,oid):
	obj = Order.objects.get(id = oid)

	context={'oinfo':obj,}

	return render(request,'home/orderinfo.html',context)


# 个人中心
def member(request):
	# 获取当前用户的所有地址信息
	address = Address.objects.filter(uid = request.session['VipUser']['uid'])
	# 获得用户的用户信息
	userinfo = Users.objects.get(id = request.session['VipUser']['uid'])

	context = {'address':address,'userinfo':userinfo}
	return render(request,'home/member.html',context)


# 个人中心新增收货地址
def addressadd(request):
	# 执行地址添加
	obj = Address()
	obj.uid = Users.objects.get(id=request.session['VipUser']['uid'])
	obj.aname = request.POST['aname']
	obj.aads = request.POST['aads']
	obj.aphone = request.POST['aphone']
	# 状态修改
	s = request.POST.get('status',0)
	# 判断当前如果设置为默认值
	if s == '1' :
		# 把其它的地址修改状态为0
		obs = Address.objects.filter(status=1)
		for x in obs:
			x.status = 0
			x.save()

	obj.status = s
	obj.save()
	return HttpResponse('<script>alert("地址添加成功");location.href="/member/"</script>')


# 收货地址删除
def addressdel(request):
	aid = request.GET['aid']

	oobjs = Order.objects.all()

	# 订单已使用的订单id 转换成字符串
	addidlist=[]
	for v in oobjs:
		addidlist.append(str(v.address.id))


	if aid in addidlist:
		return HttpResponse('<script>alert("已有订单在使用此地址，不能删除");location.href="/member/"</script>')
	else:
		obj = Address.objects.get(id=aid)
		obj.delete()


		return HttpResponse('<script>alert("地址删除成功");location.href="/member/"</script>')

# 收货地址编辑
def addressedit(request):
	aid = request.POST['aid']
	aname = request.POST['aname']
	aphone = request.POST['aphone']
	aads = request.POST['aads']
	s = request.POST.get('status',0)
	# 判断当前如果设置为默认值
	if s == '1' :
		# 把其它的地址修改状态为0
		obs = Address.objects.filter(status=1)
		for x in obs:
			x.status = 0
			x.save()

	obj = Address.objects.get(id=aid)
	obj.aname = aname
	obj.aphone = aphone
	obj.aads = aads
	obj.status = s
	obj.save()

	return HttpResponse('<script>location.href="/member/"</script>')


# 个人信息编辑
def useredit(request,uid):
	obj = Users.objects.get(id=uid)
	context = {'uinfo':obj}
	return render(request,'home/useredit.html',context)

# 个人信息执行修改
def userupdate(request):
	uid = request.POST.get('uid')
	try:
		obj = Users.objects.get(id = uid)
		obj.username = request.POST.get('username')
		obj.email = request.POST.get('email')
		obj.phone = request.POST.get('phone')
		obj.age = request.POST.get('age')
		obj.sex = request.POST.get('sex')

		# 判断是否有文件上传
		if request.FILES.get('picurl',None):

			if obj.picurl not in ['/static/pics/default/default.ico','/static/pics/default/default.jpg']:
				import os
				# 不是默认头像则删除头像文件
				os.remove('.'+obj.picurl)

			# 上传新的头像
			obj.picurl = upload(request)
		# 执行更新
		obj.save()
		return HttpResponse('<script>alert("修改成功");location.href="/member/"</script>')
	except:
		return HttpResponse('<script>alert("修改失败");location.href="/admin/user/edit/'+ str(uid) +'"</script>')




